"""
Copyright © 2023 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-ws2812-led-clock
"""
from utime import sleep_ms
from machine import SoftI2C, Pin


i2c = SoftI2C(scl=Pin(3), sda=Pin(2))
lis2dh12 = None
count_1 = count_2 = 0

def int1_double_click_callback(pin):
	global lis2dh12, count_1
	count_1 += 1
	label = ('x', 'y', 'z', 'sign', 'sc', 'dc', 'ia')

	data = i2c.readfrom_mem(0x19, 0x39, 1)[0]
	data = tuple(reversed([int(i) for i in f'{data:08b}'][1:]))

	print(f'[{count_1}]double clicked\n- {list(zip(label, data))}')

def int2_orientation_callback(pin):
	global lis2dh12, count_2
	count_2 += 1

	print(f'[{count_2}]rotated: ', end='')
	data = i2c.readfrom_mem(0x19, 0x35, 1)[0]

	direction = data & 0x3f

	if direction == 0x01:
		print(f'direction XL')
	elif direction == 0x02:
		print(f'direction XH')
	elif direction == 0x04:
		print(f'direction YL')
	elif direction == 0x08:
		print(f'direction YH')
	elif direction == 0x10:
		print(f'direction ZL')
	elif direction == 0x20:
		print(f'direction ZH')
	elif direction == 0x00:
		pass
	else:
		print(f'direction {direction}')

def reset():
	'''软复位寄存器数据'''
	i2c.writeto_mem(0x19, 0x20, bytearray(1))
	i2c.writeto_mem(0x19, 0x23, bytearray(1))

	i2c.writeto_mem(0x19, 0x1e, b'\x10')
	i2c.writeto_mem(0x19, 0x20, b'\x07')
	i2c.writeto_mem(0x19, 0x21, bytearray(5))
	i2c.writeto_mem(0x19, 0x1f, bytearray(1))
	i2c.writeto_mem(0x19, 0x26, bytearray(1))
	i2c.writeto_mem(0x19, 0x2e, bytearray(1))
	i2c.writeto_mem(0x19, 0x30, bytearray(1))
	i2c.writeto_mem(0x19, 0x32, bytearray(3))
	i2c.writeto_mem(0x19, 0x36, bytearray(3))
	i2c.writeto_mem(0x19, 0x3a, bytearray(6))

def test_double_click_and_orientation():
	i2c.writeto_mem(0x19, 0x3a, bytes([0x18]))
	i2c.writeto_mem(0x19, 0x3b, bytes([0x0c]))
	i2c.writeto_mem(0x19, 0x3c, bytes([0x06]))
	i2c.writeto_mem(0x19, 0x3d, bytes([0x70]))
	i2c.writeto_mem(0x19, 0x38, bytes([0b101010]))
	i2c.writeto_mem(0x19, 0x22, bytes([0b10000000]))

	i2c.writeto_mem(0x19, 0x36, bytes([0x36]))
	i2c.writeto_mem(0x19, 0x37, bytes([0x30]))
	i2c.writeto_mem(0x19, 0x34, bytes([0b11110011]))
	i2c.writeto_mem(0x19, 0x25, bytes([0b00100000]))
	i2c.writeto_mem(0x19, 0x21, bytes([0b00000100]))
	i2c.writeto_mem(0x19, 0x23, bytes([0b10001000]))
	i2c.writeto_mem(0x19, 0x20, bytes([0b01100111]))

	int1_pin = Pin(10, Pin.IN, Pin.PULL_UP)
	int1_pin.irq(int1_double_click_callback, trigger=Pin.IRQ_RISING)
	int2_pin = Pin(20, Pin.IN, Pin.PULL_UP)
	int2_pin.irq(int2_orientation_callback, trigger=Pin.IRQ_RISING)


if __name__ == '__main__':
	sleep_ms(10) # sensor boot time

	print(f'scanned iic device: {i2c.scan()}')

	if i2c.readfrom_mem(0x19, 0x0f, 1)[0] != 0x33:
		print('invalid lis2dh12 device id')
	else:
		reset()
		test_double_click_and_orientation()
